/*
 * @Author: wwssaabb
 * @Date: 2021-11-11 10:16:00
 * @LastEditTime: 2021-12-14 09:24:03
 * @FilePath: \handwritten-code\promise\race.js
 */


//实现promise.race 接收一个数组（不是promise的视为完成的结果），返回第一个有结果的promise ，不管是成功还是失败的结果

// const race = function (promiseArr) {
//   return new Promise((resolve, reject) => {
//     if (promiseArr.length === 0) return resolve()
//     promiseArr.forEach(p => {
//       if (p instanceof Promise) {
//         p.then(resolve, reject)
//       } else {
//         resolve(p)
//       }
//     })
//   })
// }

// const race = function (arr) {
//   return new Promise((resolve, reject) => {
//     arr.forEach(p => {
//       if (p instanceof Promise) {
//         p.then(resolve, reject)
//       } else {
//         resolve(p)
//       }
//     })
//   })
// }


const race = function (arr) {
  return new Promise((resolve, reject) => {
    arr.forEach(p => Promise.resolve(p).then(resolve, reject))
  })
}


const p1 = new Promise((resolve, reject) => setTimeout(() => {
  resolve('p1')
}, 1000))
const p2 = new Promise(resolve => setTimeout(() => {
  resolve('p2')
}, 2000))
const p3 = new Promise(resolve => setTimeout(() => {
  resolve('p3')
}, 3000))
const p4 = new Promise(resolve => setTimeout(() => {
  resolve('p4')
}, 4000))
const p5 = new Promise(resolve => setTimeout(() => {
  resolve('p5')
}, 5000))

let arr = [p1, p2, p3, p4, p5, 1, 2, false, null]; //1, 2, false, null

Promise.race(arr).then(res => console.log(res)) //
race(arr).then(res => console.log(res)) //

Promise.race([]).then(res => console.log(res))
race([]).then(res => console.log(res))